#include "statement.h"
#include <stdlib.h>
#include <string.h>

Statement* stmt_new(const char* s, const char* p, const char* o, int op) {
	Statement* result = (Statement*)malloc(sizeof(Statement));
	if (! result )
		return NULL;
	result->s = strdup(s);
	result->p = strdup(p);
	result->o = strdup(o);
	result->op = op;
	result->next = NULL;
	return result;

}


void stmt_delete(Statement* stmt) {
	Statement* next;
	if (stmt == NULL )
		return;
	if (stmt->s)
		free((void*)stmt->s);
	if (stmt->p)
		free((void*)stmt->p);
	if (stmt->o)
		free((void*)stmt->o);
	next = stmt->next;
	free((void*)stmt);
	stmt_delete(next);
}


void stmt_prepend(Statement** list, Statement* stmt)
{
	stmt->next = *list;
	*list = stmt;
}

int stmt_match(Statement* mask, Statement* stmt)
{
	if ( mask->s && strcmp(mask->s, stmt->s) )
		return 0;
	if ( mask->p && strcmp(mask->p, stmt->p) )
		return 0;
	if ( mask->o && strcmp(mask->o, stmt->o) )
		return 0;
	return 1;

}

Statement* stmt_clone(Statement* h) {
	return stmt_new(h->s, h->p, h->o, h->op);

}

void _stmt_count(Statement* h, int* count) {
	if ( h ) {
		(*count) ++;
		_stmt_count(h->next, count);
	}

}

int stmt_count(Statement* h) {
	int count = 0;
	_stmt_count(h, &count);
	return count;
}
